﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace CorporationWars
{
    [Serializable]
    public class ShareBuySellControl : UIControlBase
    {
        public StockEntity selectedStock { get; set; }

        int LineSpacing { get { return Game.Content.Load<SpriteFont>(Font).LineSpacing; } }

        public string Font { get; set; }

        public override int Width { get { return 256; } }
        public override int Height
        {

            get
            {
                if (BuyingMode)
                    return 144;
                else
                    return 160;
            }
        }

        public decimal price
        {
            get
            {
                if (BuyingMode)
                    return incDecValue * selectedStock.BuyPrice;
                else
                    return incDecValue * selectedStock.SellPrice;
            }
        }

        public decimal comm
        {
            get
            {
                return (price / 100) * Game.StockCommisionPercentage;
            }
        }

        public decimal purchaseValue
        {
            get
            {
                if (BuyingMode)
                    return price + comm;
                else
                    return price - comm;
            }
        }

        protected bool _BuyingMode { get; set; }
        public bool BuyingMode
        {
            get { return _BuyingMode; }
            set
            {
                _BuyingMode = value;
            }
        }

        public int MaxValue { get; set; }

        public int incDecValue { get; set; }

        //UIButton Increment { get; set; }
        //UIButton Decrement { get; set; }
        //UIButton Buy { get; set; }
        //UIButton Sell { get; set; }

        TimeSpan adsubStart { get; set; }
        TimeSpan adsubDuration { get; set; }
        int incdec = 1;

        Rectangle valRect { get { return new Rectangle(BGRectangle.Left + 40, BGRectangle.Top + 16, (int)DisplayValueDims.X + 16, (int)DisplayValueDims.Y + 4); } }

        string DisplayValue { get { return string.Format("{0:000000}", incDecValue); } }
        Vector2 DisplayValueDims { get { return Game.Content.Load<SpriteFont>(Font).MeasureString(DisplayValue); } }

        Vector2 PricePosition;
        Vector2 CommisionPosition;
        Vector2 TotalPosition;
        Vector2 YouHoldPosition;

        public ShareBuySellControl(Game1 game)
            : base(game)
        {
            Game = game;

            IsDragable = true;

            AddControl(new UIButton(game) { TextureAsset = "Textures/HUD/Buttons/Add", Color = Color.SteelBlue, HoverColor = Color.White, MouseDownColor = Color.LimeGreen, Name = "Add", OnClickHeld = IncDec, ToolTipText = "Add", Width = 16, Height = 16, OffSet = new Vector2(16, 18) });
            AddControl(new UIButton(game) { TextureAsset = "Textures/HUD/Buttons/Subtract", Color = Color.SteelBlue, HoverColor = Color.White, MouseDownColor = Color.Red, Name = "Subtract", OnClickHeld = IncDec, ToolTipText = "Subtract", Width = 16, Height = 16, OffSet = new Vector2(102, 18) });
            
            // Special Case buttons.
            AddControl(new UIButton(game) { TextureAsset = "Textures/HUD/Buttons/BuyButton", Color = Color.Red, HoverColor = Color.White, MouseDownColor = Color.LimeGreen, Name = "Buy", ToolTipText = "Buy", Width = 64, Height = 32 });
            AddControl(new UIButton(game) { TextureAsset = "Textures/HUD/Buttons/SellButton", Color = Color.LimeGreen, HoverColor = Color.White, MouseDownColor = Color.Red, Name = "Sell", ToolTipText = "Sell", Width = 64, Height = 32 });
        }

        protected void IncDec(UIZone sender)
        {
            if (adsubStart == TimeSpan.Zero)
                adsubStart = DateTime.Now.TimeOfDay;

            if (DateTime.Now.TimeOfDay - adsubStart > new TimeSpan(0, 0, 0, 1, 0))
            {
                adsubStart = DateTime.Now.TimeOfDay;
                incdec *= 2;
            }

            switch (((UIButton)sender).Name)
            {
                case "Add":
                    incDecValue += incdec;
                    break;
                case "Subtract":
                    incDecValue -= incdec;
                    break;
            }

            incDecValue = (int)MathHelper.Clamp(incDecValue, 0, 999999);
        }

        protected override void ButtonClicked(UIZone sender)
        {
            base.ButtonClicked(sender);

            switch (((UIButton)sender).Name)
            {
                case "Add":
                case "Subtract":
                    incdec = 1;
                    adsubStart = TimeSpan.Zero;
                    break;
                case "Buy":
                case "Sell":
                    if (OnButtonClicked != null)
                        OnButtonClicked(sender);
                    break;
            }
        }        

        public override void Update(GameTime gameTime)
        {
            if(BuyingMode)
                GetControl("Buy").OffSet = new Vector2(16, Height - 48);
            else
                GetControl("Sell").OffSet = new Vector2(16, Height - 48);

            base.Update(gameTime);
                        
            if (incDecValue > MaxValue)
                incDecValue = MaxValue;

            //Buy.Position = new Vector2(BGRectangle.Left + 16, BGRectangle.Bottom - Buy.Height - 16);
            //Sell.Position = new Vector2(BGRectangle.Left + 16, BGRectangle.Bottom - Sell.Height - 16);

            PricePosition = new Vector2(BGRectangle.Left + 16, valRect.Bottom + 8);
            CommisionPosition = new Vector2(BGRectangle.Left + 16, PricePosition.Y + LineSpacing);
            TotalPosition = new Vector2(BGRectangle.Left + 16, CommisionPosition.Y + LineSpacing);
            YouHoldPosition = new Vector2(BGRectangle.Left + 16, TotalPosition.Y + LineSpacing);

            //Increment.Update(gameTime);
            //Decrement.Update(gameTime);

            if (BuyingMode)
            {
                //Buy.Update(gameTime);
                GetControl("Buy").IsVisible = true;
                GetControl("Sell").IsVisible = false;
            }
            else
            {
                //Sell.Update(gameTime);
                GetControl("Buy").IsVisible = false;
                GetControl("Sell").IsVisible = true;
            }
        }

        
        public void Draw(GameTime gameTime)
        {
            spriteBatch.Draw(Game.Content.Load<Texture2D>("Textures/HUD/Controls/TVScreenBG"), BGRectangle, Color.White);

            // All the other bits in here..
            spriteBatch.Draw(Game.Content.Load<Texture2D>("Textures/halfwhite"), valRect, Color.White);

            Game.RenderText(DisplayValue, new Vector2(valRect.Left + 8, valRect.Top + 2), Color.Gold, -1, Font);

            
            //Increment.Draw(gameTime);
            //Decrement.Draw(gameTime);

            base.Draw(gameTime);

            if (BuyingMode)
            {
                Game.RenderText(string.Format("{0} @ {1:0.00}", selectedStock.StockName, selectedStock.BuyPrice), new Vector2(valRect.Right + 24, valRect.Top + 2), Color.White, -1, Font);

                Game.RenderText(string.Format("+{1:##0.00}%: ${0,10:#,###,##0.00}", comm, Game.StockCommisionPercentage), CommisionPosition, Color.SteelBlue, -1, Font);

                if (purchaseValue > Game.playerCorp.Funds)
                    GetControl("Buy").ToolTipText = "You can't afford this, lower the share count or raise some more liquid funds..";
                else
                    GetControl("Buy").ToolTipText = string.Format("Buy {0} {1} shares @ {2:0.00} for ${3:0.00}", incDecValue, selectedStock.StockName, selectedStock.BuyPrice, purchaseValue);

                //Buy.Draw(gameTime);
            }
            else
            {
                Color col = Color.White;

                if (selectedStock.BuyPrice > selectedStock.SellPrice)
                    col = Color.Red;
                if (selectedStock.BuyPrice < selectedStock.SellPrice)
                    col = Color.Lime;

                Game.RenderText(string.Format("{0} was {1:0.00}\n{2} @ {3:0.00}", selectedStock.StockName, selectedStock.BuyPrice, selectedStock.StockName, selectedStock.SellPrice), new Vector2(valRect.Right + 24, valRect.Top), col, -1, Font);

                Game.RenderText(string.Format("-{1:##0.00}%: ${0,10:#,###,##0.00}", comm, Game.StockCommisionPercentage), CommisionPosition, Color.SteelBlue, -1, Font);

                Game.RenderText(string.Format("You Hold: {0:000000}", selectedStock.Stocks), YouHoldPosition, Color.Wheat, -1, Font);
                GetControl("Sell").ToolTipText = string.Format("Sell {0} {1} shares @ {2:0.00} for ${3:0.00}", incDecValue, selectedStock.StockName, selectedStock.SellPrice, purchaseValue);

                //Sell.Draw(gameTime);
            }

            Game.RenderText(string.Format("Price  : ${0,10:#,###,##0.00}", price), PricePosition, Color.Yellow, -1, Font);            
            Game.RenderText(string.Format("Total  : ${0,10:#,###,##0.00}", purchaseValue), TotalPosition, Color.White, -1, Font);

            if (BuyingMode)
                spriteBatch.Draw(Game.Content.Load<Texture2D>("Textures/HUD/Controls/TVScreenFG"), BGRectangle, Color.Green);
            else
                spriteBatch.Draw(Game.Content.Load<Texture2D>("Textures/HUD/Controls/TVScreenFG"), BGRectangle, Color.Red);
        }

        public virtual void ReWire(Game1 game)
        {
            Game = game;

            GetControl("Add").OnClickHeld = IncDec;
            //Increment.OnClick = IncDecEnd;

            GetControl("Subtract").OnClickHeld = IncDec;
            //Decrement.OnClick = IncDecEnd;

            //Buy.OnClick = IncDecEnd;
            //Sell.OnClick = IncDecEnd;
        }

        public virtual void UnWire()
        {

            GetControl("Add").OnClickHeld = null;
            //Increment.OnClick = IncDecEnd;

            GetControl("Subtract").OnClickHeld = null;
            //Increment.OnClickHeld = null;
            //Increment.OnClick = null;

            //Decrement.OnClickHeld = null;
            //Decrement.OnClick = null;

            //Buy.OnClick = null;
            //Sell.OnClick = null;
            
        }
    }
}
